<template>
  <div class="base-form-container">
    <el-divider>基本信息</el-divider>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="baseFormRef"
      label-width="100px"
      class="base-form"
    >
      <el-form-item
        label="编码"
        prop="nodeCode"
      >
        <el-input
          v-model="ruleForm.nodeCode"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item
        label="名称"
        prop="name"
      >
        <el-input
          v-model="ruleForm.name"
          :disabled="!canEdit"
        ></el-input>
      </el-form-item>
    </el-form>
    <div
      v-if="canEdit"
      class="footer"
    >
      <el-button
        type="primary"
        @click="submitForm"
      >保存</el-button>
    </div>
  </div>
</template>
<script>
import { saveTreeNode } from '@/api/import/template'
import { NODE_TYPE } from '../enum'
export default {
  name: 'import-template-baseform',
  props: {
    data: {
      type: Object,
      default: null
    },
    canEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      ruleForm: {
        nodeCode: '',
        name: ''
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.baseFormRef.validate((valid) => {
        if (valid) {
          const { name } = this.ruleForm
          const { parentId, nodeCode, id } = this.data
          const param = {
            parentId,
            nodeName: name,
            nodeType: NODE_TYPE.GROUP
          }
          if (id) {
            param.id = id
            param.nodeCode = nodeCode
          }
          saveTreeNode(param).then((res) => {
            this.$message.success('保存成功！')
            this.$emit('save-success', res)
          })
        } else {
          return false
        }
      })
    }
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        this.ruleForm = {
          nodeCode: newVal.nodeCode || '',
          name: newVal.name || ''
        }
      },
      deep: true
    }
  }
}
</script>
<style lang="scss" scoped>
.base-form-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.base-form {
  overflow: hidden;
  .el-form-item {
    width: 50%;
    float: left;
  }
}
.footer {
  position: absolute;
  bottom: 0;
  right: 0;
}
</style>